/** @jsxImportSource react */

import { qwikify$ } from '@builder.io/qwik-react';
import { type PostCollection } from '@prisma/client';
import { useEffect, useState } from 'react';
import { type Result } from '~/common/types';
import CollectionCreator from './CollectionCreator';
import CollectionUpdator from './CollectionUpdator';
import _ from 'lodash';
import { Skeleton } from '~/components/react/shadcn/ui/skeleton';
import { Button } from '~/components/react/shadcn/ui/button';

type MyPostCollectionsProps = {
  onLoadAll: () => Promise<Result<PostCollection[], string>>;
  onNavigate: (url: string) => void;
  onCreate: (title: string) => Promise<PostCollection>;
  onUpdate: (id: bigint, title: string) => Promise<void>;
};

type CollectionsResult =
  | { status: 'loaded'; collections: PostCollection[] }
  | { status: 'loading' }
  | { status: 'error'; error: string };

function MyPostCollections({ onLoadAll, onNavigate, onCreate, onUpdate }: MyPostCollectionsProps) {
  const [collectionResult, setCollectionResult] = useState<CollectionsResult>({ status: 'loading' });
  const [updatingCollection, setUpdatingCollection] = useState<PostCollection | null>(null);

  const load = () => {
    setCollectionResult({ status: 'loading' });
    onLoadAll().then((result) => {
      if (result.ok) {
        setCollectionResult({ status: 'loaded', collections: result.data });
      } else {
        setCollectionResult({ status: 'error', error: result.error });
      }
    });
  };

  useEffect(() => {
    load();
  }, []);

  if (collectionResult.status === 'loading') {
    return (
      <div className="space-y-2">
        <Skeleton className="bg-kq-100 h-8 w-full" />
        <Skeleton className="bg-kq-100 h-8 w-full" />
        <Skeleton className="bg-kq-100 h-8 w-full" />
      </div>
    );
  } else if (collectionResult.status === 'error') {
    return (
      <div>
        加载失败: {collectionResult.error} <Button onClick={load}>点此重新加载</Button>
      </div>
    );
  } else {
    const { collections } = collectionResult;
    return (
      <div>
        <h1 className="font-bold border-b-2 border-kq-200 py-3 px-2 flex justify-between items-center">
          分类
          <CollectionCreator
            onCreate={async (title) => {
              const collection = await onCreate(title);
              setCollectionResult({ status: 'loaded', collections: [collection, ...collections] });
            }}
          />
        </h1>
        <div>
          {collections.map((collection) => (
            <div
              key={collection.id}
              className="border-t border-kq-200 py-3 px-2 cursor-pointer hover:bg-kq-100 flex justify-between"
            >
              <span onClick={() => onNavigate(`/me/post-collections/${collection.id.toString()}`)}>
                {collection.title}
              </span>
              <span
                className="text-sm text-kq-500 cursor-pointer hover:text-kq-700"
                onClick={() => {
                  setUpdatingCollection(collection);
                }}
              >
                修改
              </span>
            </div>
          ))}
        </div>
        {updatingCollection && (
          <CollectionUpdator
            id={updatingCollection.id}
            title={updatingCollection.title}
            onOpenChange={(open) => {
              if (!open) {
                setUpdatingCollection(null);
              }
            }}
            onUpdate={async (id, title) => {
              await onUpdate(id, title);
              setUpdatingCollection(null);
              const newCollections = _.cloneDeep(collections);
              newCollections.filter((it) => it.id === id)[0].title = title;
              setCollectionResult({ status: 'loaded', collections: newCollections });
            }}
            open={!!updatingCollection}
          />
        )}
      </div>
    );
  }
}

export const QMyPostCollections = qwikify$(MyPostCollections);
